<template>
  <ActionPanel :loading="loading">
    <div>
      <ElButton type="primary" link @click="actionLookupRef.show()">
        {{ currentNode ? currentNode.fullLabel : '选择功能' }}
      </ElButton>
      <ActionLookup ref="actionLookupRef" v-model="currentNode" :data="getDataActions()" />
      <el-table v-if="currentNode" :data="operateList" width="100" height="300">
        <el-table-column label="列">
          <template #default="{ row }">
            <el-tree-select v-model="row.field" :data="declareds" node-key="value" placeholder="请选择">
              <template #default="{ data: { label } }">
                {{ label }}
              </template>
            </el-tree-select>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-select v-model="row.op" placeholder="请选择">
              <el-option v-for="(label, value) in getOps()" :value="value" :label="label" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="值">
          <template #default="{ row }">
            <el-input v-model="row.value" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column width="80">
          <template #header>
            <ElButton type="primary" size="small" @click="addRow">+</ElButton>
          </template>
          <template #="{ $index }">
            <ElButton type="danger" size="small" @click="removeRow($index)">-</ElButton>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <div class="flex justify-center items-center">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </template>
  </ActionPanel>
</template>
<script setup lang="ts">
  import { ElTreeSelect, ElButton, ElInput, ElSelect, ElOption, ElTable, ElTableColumn } from 'element-plus'
  import { ref, onMounted, watch, computed, nextTick, inject } from 'vue'
  import feedback from '@/utils/feedback'
  import { Action, getOps, OpType } from '@/seed-application/types'
  import { getDataActions } from '@/seed-application'
  import { put } from '@/utils/request'
  import { getUrl } from "@/seed-application/utils/ActionUtil";
  import { ActionLookup } from '@/components/ActionLookup'
  import { get } from '@/utils/request'
  import { getDeclaresTree } from '@/seed-application/utils/ActionUtil'
  import ActionPanel from '@/components/ActionPanel/src/ActionPanel.vue'
  import { closePopupKey } from '@/components/Popup'
import { serialize } from 'v8'

  const props = defineProps<{action: Action, id: string}>()
  const action = props.action

  const actionLookupRef = ref()
  const currentNode = ref()
  const operateList = ref<{field?: string, op?: OpType, value?: any}[]>([])

  const addRow = () => operateList.value.push({})
  const removeRow = (index) => operateList.value.splice(index, 1)
  const declareds = computed(() => currentNode.value ? getDeclaresTree(currentNode.value.action) : [])
console.log('declareds=====', declareds)
console.log('currentNode.value', currentNode.value)

  function deserialize(items: string[]) {
    const ret = []
    for(const item of items) {
      const [declareAndOp, value] = item.split('=')
      const pos = declareAndOp.lastIndexOf('_')
      const field = declareAndOp.substring(0, pos)
      const op = declareAndOp.substring(pos + 1)

      ret.push({ field, op, value })
    }

    return ret
  }

  function serialize(list: {field?: string, op?: OpType, value?: any}[]) {
    const ret: string[] = []
    for(const item1 of list) {
      const { field, op, value } = item1
      let item = `${field}_${op}`
      if(value) item = item + '=' + value;

      ret.push(item)
    }

    return ret
  }

  const loading = ref(false)
  watch(() => currentNode.value, async (value) => {
    loading.value = true
    const res = await get(`${getUrl(action)}/${props.id}`, {actionPath: value.value})
    operateList.value = deserialize(res)
    if(operateList.value.length == 0) addRow()
    loading.value = false
  })

  const close = inject<() => void>(closePopupKey, void 0)
  const save = async () => {
    if(operateList.value.length == 0) {
      feedback.alertError('没有任何可保存的数据')
      return
    }

    for(const i in operateList.value) {
      const operate = operateList.value[i]
      const pos = parseInt(i) + 1
      if(!operate.field) {
        feedback.alertError(`第【${pos}】行【列】不能为空`)
        return
      }
      if(!operate.op) {
        feedback.alertError(`第【${pos}】行【操作】不能为空`)
        return
      }
    }
    
    loading.value = true
    await put(`${getUrl(action)}?id=${props.id}&actionPath=${currentNode.value.value}`, serialize(operateList.value))
    loading.value = false
    close?.()
    feedback.msgSuccess(`${action.label}成功`)
  }

  onMounted(() => nextTick(() => actionLookupRef.value.show()))
</script>